package cn.com.dycc.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
/**
 * 数据库工具类
 * @author gaofan
 *
 */
public class DBUtil {
	//连接池
	private static BasicDataSource bs;
	//线程仓库
	private static ThreadLocal<Connection> tl;
	//初始化
	static{
		bs=new BasicDataSource();
		tl=new ThreadLocal<Connection>();
		Properties ps=new Properties();
		try {
			ps.load(DBUtil.class.getClassLoader().getResourceAsStream("db/db.properties"));
			bs.setDriverClassName(ps.getProperty("driver"));
//			System.out.println(ps.getProperty("driver"));
			bs.setUrl(ps.getProperty("url"));
//			System.out.println(ps.getProperty("url"));
			bs.setUsername(ps.getProperty("user"));
//			System.out.println(ps.getProperty("user"));
			bs.setPassword(ps.getProperty("password"));
//			System.out.println(ps.getProperty("password"));
			bs.setMaxActive(Integer.parseInt(ps.getProperty("maxSize")));
			//bs.setMaxWait(Long.parseLong(ps.getProperty("maxWait")));
//			System.out.println(ps.getProperty("password"));
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("找不到配置文件",e);
		}
		
	}
	/**
	 * 获得数据库连接
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException{
		Connection conn=bs.getConnection();
		tl.set(conn);
		return conn;
	}
	/**
	 * 取消自动提交
	 */
	public static void cancelToAuto(){
		try {
			tl.get().setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("设置手动提交失败",e);
		}
		
	}
	/**
	 * 数据库回滚
	 */
	public static void transBollback(){
		try {
			tl.get().rollback();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("回滚失败",e);
		}
	}
	/**
	 * 手动提交
	 */
	public static void transCommit(){
		try {
			tl.get().commit();
			tl.get().setAutoCommit(true);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("提交失败",e);
		}
	}
	/**
	 * 归还连接
	 */
	public static void close(){
		Connection conn=tl.get();
		//transCommit();
		tl.remove();
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException("归还连接失败",e);
			}
		}
		
	}

}
